package com.yksj.healthtalk.ui.doctorstation.service;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.adapter.DoctorServiceDataListAdapter;
import com.yksj.healthtalk.adapter.DoctorServiceDataListAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.doctorstation.DoctorSendMessageToPatients;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.ViewUtils;

/**
 * 患者管理  我的患者
 * @author jack_tang
 *
 */
public class DoctorServiceGroupMenberActivity extends BaseFragmentActivity implements OnClickListener, OnRefreshListener<ListView>, OnItemClickListener, onClickFriendAttentionListener{
	
	PullToRefreshListView mPullToRefreshListView;
	ListView mPullListView;
	PopupWindow mMenuWindow;
	DoctorServiceDataListAdapter mAdapter;
	PopMenuListAdapter mPopMenuListAdapter;
	ListView mListView;
	String mCurrentGroup = "0";//当前分组
	String userId;
	private IntentFilter filter;
	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
			LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(DoctorServiceGroupMenberActivity.this, R.string.groupNewFail);
				} else if (result.equals("-1")) {
					ToastUtil.showShort(DoctorServiceGroupMenberActivity.this,R.string.against__blacklist_operations);
				} else {
					initData();
				}
				
			}
		}
	};
	
	Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			mPullListView.setSelection(0);
		};
	};
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_service_group_menmer_layout);
		userId = SmartFoxClient.getLoginUserId();
		if(arg0 != null){
			mCurrentGroup = arg0.getString("mCurrentGroup");
		}
		initUI();
	}
	
	

	@Override
	public void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}

	@Override
	public void onStart() {
		filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		registerReceiver(receiver, filter);
		super.onStart();
	}
	
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("mCurrentGroup", mCurrentGroup);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		initData();
	}
	
	private void initUI(){
		initTitle();
		titleTextV.setOnClickListener(this);
		setBackBtn("返回",this);
		titleTextV.setText("我的患者");
		titleTextV.setCompoundDrawablesWithIntrinsicBounds(0,0, R.drawable.arrows_down,0);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setText("分组管理");
		titleRightBtn2.setOnClickListener(this);
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.pull_refresh_listview);
		mAdapter = new DoctorServiceDataListAdapter(this);
		mAdapter.setonClickFriendAttentionListener(this);
		mPullListView = mPullToRefreshListView.getRefreshableView();
		mPullListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.list_line_layout, null));
		mPullListView.setAdapter(mAdapter);
		mPullListView.setOnItemClickListener(this);
		mPopMenuListAdapter = new PopMenuListAdapter();
		mPullToRefreshListView.setOnRefreshListener(this);
		findViewById(android.R.id.button1).setOnClickListener(this);
	}
	
	private void initData(){
		HttpRestClient.doHttpQueryGroups(userId, "5","1",String.valueOf(Integer.MAX_VALUE), "", mCurrentGroup, new JsonsfHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {//{"error_code":"100110","error_message":"网络出现问题，请稍后再试"}
				if(response.containsKey("error_message")){
					ToastUtil.showToastPanl(response.getString("error_message"));
				}else{
					JSONArray array = response.getJSONArray("patientGroupInfo");
					JSONObject object = new JSONObject();
					object.put("PATIENT_GROUP_ID", "0");
					object.put("PATIENT_GROUP", "我的患者");
					array.add(0,object);
					mPopMenuListAdapter.onDataChange(array);
					ViewUtils.setGone(findViewById(android.R.id.button1),response.getJSONArray("dataList").size()<=0);
					mAdapter.onDataChange(response.getJSONArray("dataList"));
					handler.sendEmptyMessage(0);
				}

			}
			@Override
			public void onFinish() {
				super.onFinish();
				mPullToRefreshListView.onRefreshComplete();
			}
			@Override
			public void onStart() {
				super.onStart();
				mPullToRefreshListView.setRefreshing();
			}
		});
	}
	
	private void onShowFilterDialogMenu(){
		if(mMenuWindow == null){
			View view = getLayoutInflater().inflate(R.layout.window_menu_filter_group_layout,null);
			mMenuWindow = new PopupWindow(view,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,true);
			mMenuWindow.setTouchable(true);
			mMenuWindow.setBackgroundDrawable(new BitmapDrawable());
			mMenuWindow.setOutsideTouchable(true);
			mMenuWindow.setContentView(view);
			mListView = (ListView)view.findViewById(android.R.id.list);
			mListView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
					mMenuWindow.dismiss();
					JSONObject jsonObject = (JSONObject)arg0.getAdapter().getItem(arg2);
					String groupid = jsonObject.getString("PATIENT_GROUP_ID");
					if(groupid.equals(mCurrentGroup))return;
					titleTextV.setText(jsonObject.getString("PATIENT_GROUP"));
					mCurrentGroup = groupid;
					initData();
				}
			});
		}
		mListView.setAdapter(mPopMenuListAdapter);
		mMenuWindow.showAtLocation(titleTextV,Gravity.TOP, 0, (titleTextV.getMeasuredHeight()*2));
	}
	
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_right2://分组管理
			Intent intent = new Intent(this,DoctorServiceGroupEditorActivity.class);
			startActivityForResult(intent,0);
			break;
		case R.id.title_lable:
			onShowFilterDialogMenu(); 
			break;
		case android.R.id.button1://给患者发通知
			StringBuffer buffer=new StringBuffer();
			ArrayList<String> ids=new ArrayList<String>();
			for (int i = 0; i < mAdapter.mArray.size(); i++) {
				String id=mAdapter.mArray.getJSONObject(i).getString("customerId");
				buffer.append(id);
				buffer.append(",");
				ids.add(id);
			}
			if(buffer.length()<=0)return;
			intent=new Intent(this,DoctorSendMessageToPatients.class);
			intent.putExtra("id", mCurrentGroup);
			intent.putStringArrayListExtra("ids", ids);
			startActivity(intent);
			break;
		case R.id.title_back:
			setResult(RESULT_OK, getIntent());
			finish();
			break;
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		mPullToRefreshListView.onRefreshComplete();
	}
	
	class PopMenuListAdapter extends BaseAdapter{
		JSONArray mArray = new JSONArray();
		
		public void onDataChange(JSONArray array){
			this.mArray = array;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mArray.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return mArray.getJSONObject(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null){
				convertView = getLayoutInflater().inflate(R.layout.commn_txtview_item_layout, null);
			}
			String name = getItem(position).getString("PATIENT_GROUP");
			((TextView)convertView).setText(name);
			return convertView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			JSONObject jsonObject = mAdapter.getItem(position-1);
			CustomerInfoEntity entity=new CustomerInfoEntity();
			entity.setId(jsonObject.getString("customerId"));
			if("".equals(jsonObject.getString("remarksName"))){
				entity.setName(jsonObject.getString("customerNickname"));
			}else{
				entity.setName(jsonObject.getString("remarksName"));
			}
			
			FriendHttpUtil.onItemClick(this, entity);
		} catch (Exception e) {
		}
	}



	@Override
	public void onClickFriendAttention(int attentioned,CustomerInfoEntity entity) {
		FriendHttpUtil.requestAttentionTofriends(this,null, entity);
	}
	
}
